package com.de.controller;

import com.de.entity.AjaxResult;
import com.de.rtsp.MediaTransfer;
import com.de.rtsp.MediaVideoTransfer;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FrameGrabber;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;


@Slf4j
@Controller
public class IndexController {
    public static ConcurrentHashMap<String, MediaTransfer> mediaTransfers = new ConcurrentHashMap<>();

    @GetMapping("startVideo")
    @ResponseBody
    public AjaxResult startVideo(@RequestParam("rtsp") String rtsp,@RequestParam("id") String id) {
        // 检查是否已经存在相同的流
        for (Map.Entry<String, MediaTransfer> entry : mediaTransfers.entrySet()) {
            if (entry.getKey().equals(id)) {
                return AjaxResult.success(entry.getKey()); // 返回已有流的 ID
            }
        }
        // 如果不存在，则创建新的流
        MediaTransfer mediaTransfer = new MediaTransfer(); // 创建新实例
        mediaTransfer.setRtspUrl(rtsp);
        mediaTransfer.startStreaming(id); // 开始推流
        mediaTransfers.put(id, mediaTransfer); // 存储实例
        return AjaxResult.success(id); // 返回 ID 给客户端
    }

    @GetMapping("stopVideo")
    @ResponseBody
    public AjaxResult stopVideo(@RequestParam String id) {
        MediaTransfer mediaTransfer = mediaTransfers.get(id); // 获取实例
        if (mediaTransfer != null) {
            //停止推流
            mediaTransfer.stopStreaming();
            FFmpegFrameGrabber grabber = mediaTransfer.getGrabber();
            mediaTransfer.stopGrabber(grabber);
            //删除引用
            mediaTransfers.remove(id);
            return AjaxResult.success();
        } else {
            return AjaxResult.error("未找到流");
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
        IndexController indexController = new IndexController();
        indexController.startVideo("rtsp://admin:cctv@600476@192.168.100.20:554/Streaming/Channels/102","1");
    }
}
